package com.zdkj.subway.stm.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.admin.api.entity.SysDictItem;
import com.zdkj.common.core.constant.CommonConstants;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.subway.stm.constant.StmConstans;
import com.zdkj.subway.stm.constant.StmTableCommon;
import com.zdkj.subway.stm.dto.in.CommomConfirmInfoDTO;
import com.zdkj.subway.stm.dto.in.SwStMarketingTicketDTO;
import com.zdkj.subway.stm.dvo.SwStmStationDataEntryLogDvo;
import com.zdkj.subway.stm.entity.SwStElectronicReceiptDetails;
import com.zdkj.subway.stm.entity.SwStMarketingTicket;
import com.zdkj.subway.stm.entity.SwStmStationDataEntryLog;
import com.zdkj.subway.stm.fegin.SystemUserService;
import com.zdkj.subway.stm.mapper.SwStMarketingTicketMapper;
import com.zdkj.subway.stm.service.SwStElectronicReceiptDetailsService;
import com.zdkj.subway.stm.service.SwStElectronicReceiptService;
import com.zdkj.subway.stm.service.SwStMarketingTicketService;
import com.zdkj.subway.stm.service.SwStmStationDataEntryLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 营销车票录入主表
 *
 * @author songtuo
 * @date 2020-07-11 21:43:57
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swstmarketingticket")
@Api(value = "swstmarketingticket", tags = "营销车票录入主表管理")
@Slf4j
public class SwStMarketingTicketController {

    private final SwStMarketingTicketService swStMarketingTicketService;
    private final SwStMarketingTicketMapper swStMarketingTicketMapper;

    private final SystemUserService systemUserService;

    private final SwStElectronicReceiptService detailsEleService;

    @Autowired
    SwStElectronicReceiptDetailsService elesubDetailsEleService;

    private final SwStmStationDataEntryLogService swStmStationDataEntryLogService;
    /**
     * 分页查询
     *
     * @param page                分页对象
     * @param swStMarketingTicket 营销车票录入主表
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwStMarketingTicketPage(Page page, SwStMarketingTicket swStMarketingTicket) {
        List<String> dateCondition = swStMarketingTicket.getDates1();
        SwStMarketingTicket swStMarketingTicketObj = ObjectUtils.getDefaultObj(SwStMarketingTicket.class);
        swStMarketingTicket.setLineCode(swStMarketingTicketObj.getLineCode());
        swStMarketingTicket.setStationCode(swStMarketingTicketObj.getStationCode());
        //LambdaQueryWrapper<SwStMarketingTicket> queryWrapper = Wrappers.query(swStMarketingTicket).lambda();
        //QueryWrapper<SwStMarketingTicket> queryWrapper = Wrappers.query(swStMarketingTicket);

		String conductorJobNo = swStMarketingTicket.getConductorJobNo();
        swStMarketingTicket.setConductorJobNo(null);//先置空，下面的查询才能起作用
		swStMarketingTicket.setConductorName(null);
        QueryWrapper<SwStMarketingTicket> queryWrapper = Wrappers.query(swStMarketingTicket);
        if(StringUtils.isNotEmpty(swStMarketingTicket.getSourceQueryFlag()) && StringUtils.isNotEmpty(conductorJobNo)){
            queryWrapper.lambda().eq(SwStMarketingTicket::getConductorJobNo,conductorJobNo);//报表路径跳转
        }
        if(StringUtils.isEmpty(swStMarketingTicket.getSourceQueryFlag()) && StringUtils.isNotEmpty(conductorJobNo)){
            queryWrapper.lambda().like(SwStMarketingTicket::getConductorJobNo,conductorJobNo);//售票员工号模糊匹配
        }
        queryWrapper.orderByDesc("OPERTOR_TIME");
        if (ObjectUtil.isNotEmpty(dateCondition)) {
            queryWrapper.lambda().between(SwStMarketingTicket::getOpertorTime, dateCondition.get(0), dateCondition.get(1));
        }
        return R.ok(swStMarketingTicketService.page(page, queryWrapper));
    }


    /**
     * 通过id查询营销车票录入主表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swStMarketingTicketService.getById(id));
    }

    /**
     * 新增营销车票录入主表
     *
     * @param swStMarketingTicketDTO 营销车票录入主表
     * @return R
     */
    @ApiOperation(value = "新增营销车票录入主表", notes = "新增营销车票录入主表")
    //@SysLog("新增营销车票录入主表")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('swstmarketingticket_add')")
    public R save(@RequestBody SwStMarketingTicketDTO swStMarketingTicketDTO) {
        return R.ok(swStMarketingTicketService.saveSwStMarketingTicket(swStMarketingTicketDTO));
    }

    /**
     * 修改营销车票录入主表
     *
     * @param swStMarketingTicketDTO 营销车票录入主表
     * @return R
     */
    @ApiOperation(value = "修改营销车票录入主表", notes = "修改营销车票录入主表")
    //@SysLog("修改营销车票录入主表")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('swstmarketingticket_edit')")
    public R updateById(@RequestBody SwStMarketingTicketDTO swStMarketingTicketDTO) {
        SwStMarketingTicket marketingTicket = swStMarketingTicketService.getById(swStMarketingTicketDTO.getMarketingTicket().getId());
        if(ObjectUtil.isNotEmpty(marketingTicket)){
            String approvalStatus = marketingTicket.getApprovalStatus();
            if("1".equals(approvalStatus)){
                return R.failed(StmConstans.failedEdit);
            }
        }
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("line_code",swStMarketingTicketDTO.getMarketingTicket().getLineCode());
        queryWrapper.eq("station_code",swStMarketingTicketDTO.getMarketingTicket().getStationCode());
        queryWrapper.eq("CONDUCTOR_JOB_NO",swStMarketingTicketDTO.getMarketingTicket().getConductorJobNo());
        queryWrapper.eq("CONDUCTOR_SHIFTS",swStMarketingTicketDTO.getMarketingTicket().getConductorShifts());
        queryWrapper.eq("DEVICE_OPERATE_NUM",swStMarketingTicketDTO.getMarketingTicket().getDeviceOperateNum());
        queryWrapper.eq("DATE_FORMAT(OPERTOR_TIME, '%Y-%m-%d')",swStMarketingTicketDTO.getMarketingTicket().getOpertorTime());
        queryWrapper.eq("del_flag","0");
        queryWrapper.ne("id",swStMarketingTicketDTO.getMarketingTicket().getId());
        int count=swStMarketingTicketService.count(queryWrapper);
        if(count>0){
            return R.failed(count,swStMarketingTicketDTO.getMarketingTicket().getConductorName()+"在"+swStMarketingTicketDTO.getMarketingTicket().getOpertorTime()+" 该班次的数据已存在,不允许修改为该售票员的数据！");
        }
        return R.ok(swStMarketingTicketService.updateStMarketingTicket(swStMarketingTicketDTO));
    }

    /**
     * 通过id查询营销车票录入主表历史记录
     *
     * @param  id
     * @return R
     */
    @ApiOperation(value = "通过id查询营销车票录入主表历史记录", notes = "通过id查询营销车票录入主表历史记录")
    @GetMapping("getLogById/{id}")
    public R getLogById(@PathVariable("id") Integer id) {
        List<SwStmStationDataEntryLogDvo> LogInfoList = new ArrayList<>();
        List<SwStmStationDataEntryLog> swStmStationDataEntryLogs = swStmStationDataEntryLogService.getBaseMapper()
                .selectList(Wrappers.<SwStmStationDataEntryLog>lambdaQuery()
                        .eq(SwStmStationDataEntryLog::getRelationId, id)
                        .eq(SwStmStationDataEntryLog::getLogTableName, StmTableCommon.SW_ST_MARKETING_TICKET));
        //返回json串
        if(CollectionUtil.isNotEmpty(swStmStationDataEntryLogs)){
            swStmStationDataEntryLogs.stream().forEach(x -> {
                JSONObject jsonObject = JSONObject.parseObject(x.getLogInfo());
                SwStmStationDataEntryLogDvo swStmStationDataEntryLogDvo = new SwStmStationDataEntryLogDvo();
                BeanUtils.copyProperties(x,swStmStationDataEntryLogDvo);
                swStmStationDataEntryLogDvo.setLogInfo(jsonObject);
                LogInfoList.add(swStmStationDataEntryLogDvo);
            });
        }
        //List<String> LogInfoList = swStmStationDataEntryLogs.stream().map(SwStmStationDataEntryLog::getLogInfo).collect(Collectors.toList());
        return R.ok(LogInfoList);
    }

    /**
     * 通过记录表id查询日营销数据详情历史记录
     *
     * @param  id
     * @return R
     */
    @ApiOperation(value = "通过记录表id查询日营销数据详情历史记录", notes = "通过记录表id查询日营销数据详情历史记录")
    @GetMapping("getLogChildById/{id}")
    public R getLogChildById(@PathVariable("id") Integer id) {
        return R.ok(swStmStationDataEntryLogService.mapListMarketingTicket(id));
    }

    /**
     * 通过id删除营销车票录入主表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除营销车票录入主表", notes = "通过id删除营销车票录入主表")
    //@SysLog("通过id删除营销车票录入主表")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('swstmarketingticket_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(swStMarketingTicketService.deleteCascadeById(id));
    }

    /**
     * 查询日结账单详情
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询日营销数据详情", notes = "通过id查询")
    @GetMapping("/details/{id}")
    public R queryMarketingTicketDetailsById(@PathVariable("id") Integer id) {
        return R.ok(swStMarketingTicketService.queryDetailsById(id));
    }

    /**
     * 通过id批量删除营销车票录入主表
     *
     * @param idList id
     * @return R
     */
    @ApiOperation(value = "通过id批量删除营销车票录入主表", notes = "通过id删除营销车票录入主表")
    //@SysLog("通过id删除营销车票录入主表")
    @PostMapping("/batchDelete")
    @Transactional
    @PreAuthorize("@pms.hasPermission('swstmarketingticket_batch_del')")
    public R batchRemoveById(@RequestBody List<Integer> idList) {
        List<SwStMarketingTicket> list = swStMarketingTicketService.list(new QueryWrapper<SwStMarketingTicket>().lambda().in(SwStMarketingTicket::getId, idList));
        List<Integer> deleteIds = list.stream().filter(x -> !x.getApprovalStatus().equals(CommonConstants.SUBMIT)).map(x -> x.getId()).collect(Collectors.toList());
        if(CollectionUtil.isEmpty(deleteIds)){
            return R.failed(StmConstans.failedDelete);
        }
        List<Integer> deleteEleIds = list.stream().filter(x -> !x.getApprovalStatus().equals(CommonConstants.SUBMIT)).map(x -> x.getRefElectronicPreviewId()).collect(Collectors.toList());
        //删除电子回执单子表
        List<SwStElectronicReceiptDetails> elesubList = elesubDetailsEleService.list(new QueryWrapper<SwStElectronicReceiptDetails>().lambda().in(SwStElectronicReceiptDetails::getRelationId, deleteEleIds));
        if(CollectionUtil.isNotEmpty(elesubList)){
            elesubList.forEach(elesubDetailsEleService::removeById);
        }
        deleteIds.forEach(swStMarketingTicketService::deleteCascadeById);
        if(CollectionUtil.isNotEmpty(deleteEleIds)){
            deleteEleIds.forEach(detailsEleService::removeById);
        }

        return R.ok();
    }

    /**
     * 查询需要确认的营销车票数据
     *
     * @param confirmInfoDTO 查询需要确认的营销车票数据
     * @return R
     */
    @ApiOperation(value = "查询需要确认的营销车票数据", notes = "查询需要确认的营销车票数据")
    //@SysLog("查询需要确认的营销车票数据")
    @PostMapping("/query/needConfirmData")
    public R queryNeedToConfirmData(@RequestBody CommomConfirmInfoDTO confirmInfoDTO) {
        return R.ok(swStMarketingTicketService.queryNeedToConfirmData(confirmInfoDTO));
    }

    /**
     * 营销车票数据确认
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "营销车票数据确认", notes = "营销车票数据确认")
    @GetMapping("/confirm/{id}")
    @PreAuthorize("@pms.hasPermission('swstmarketingticket_confirm')")
    public R confirmData(@PathVariable("id") Integer id) {
        return R.ok(swStMarketingTicketService.confirmData(id));
    }

    @ApiOperation(value = "导出日营销车票数据", notes = "导出日营销车票数据")
    @GetMapping("/export")
    public void export(Page page, SwStMarketingTicket swStMarketingTicket, HttpServletResponse response) {
        List<SwStMarketingTicket> records = swStMarketingTicketService.page(page, Wrappers.query(swStMarketingTicket)).getRecords();
        R<List<SysDictItem>> inputDataStatus = systemUserService.getDictByType(StmConstans.STM_INPUT_DATA_STATUS);
        List<SysDictItem> dictData = inputDataStatus.getData();
        try {
            if (CollectionUtil.isNotEmpty(records)) {
                Map<String, String> map = dictData.stream().collect(Collectors.toMap(SysDictItem::getValue, SysDictItem::getLabel));
                for (SwStMarketingTicket record : records) {
                    record.setApprovalStatus(map.get(record.getApprovalStatus()));
                }
            }
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("日营销车票数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
            EasyExcel.write(response.getOutputStream(), SwStMarketingTicket.class).
                    sheet("日营销车票数据").doWrite(records);
        } catch (IOException e) {
            log.error("导出日营销车票数据");
        }
    }

    /**
     * 批量提交营销车票装填
     *
     * @param ids
     * @param status
     * @return
     */
    @ApiOperation(value = "批量提交营销车票状态", notes = "批量提交营销车票状态")
    @GetMapping("/approval/status")
    @PreAuthorize("@pms.hasPermission('swstmarketingticket_approval_status')")
    public R confirmData(@RequestParam("ids") List<Integer> ids, @RequestParam("status") String status) {
        return R.ok(swStMarketingTicketService.updateApprovalStatus(ids, status));
    }
    /**
     * 营销车票通过被合并的数据ID查询合并之前的记录
     *
     * @param
     * @return R
     */
    @ApiOperation(value = "通过被合并的数据ID查询合并之前的记录", notes = "通过被合并的数据ID查询合并之前的记录")
    @GetMapping("getMergeBeforById/{id}")
    public R getMergeBeforById(@PathVariable("id") Integer id) {
        SwStMarketingTicket marketingTicket = swStMarketingTicketService.getById(id);
        if(ObjectUtil.isNotEmpty(marketingTicket)){
            String isBeMergedId = marketingTicket.getIsBeMergedId();
            String[] split = isBeMergedId.split(",");
            List<SwStMarketingTicket> list = swStMarketingTicketMapper.getList(split);
            return R.ok(list);
        }else {
            return R.failed("无合并数据！");
        }
    }

}
